package com.warm.pump.executor.batch;

import com.warm.pump.frame.db.DbUtil;
import com.warm.pump.module.work.bean.po.gen.WorkItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.CustomParsedSql;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterUtils;
import org.springframework.jdbc.core.namedparam.ParsedSql;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CursorWriter implements ItemWriter<Object> {
    private static final Logger log = LoggerFactory.getLogger(CursorWriter.class);
    private WorkItem itemDtl;

    private boolean fail = false;

    public void setFail(boolean fail) {
        this.fail = fail;
    }

    /**
     * @see ItemWriter#write(List)
     */
    public void write(List<? extends Object> data) throws Exception {
        //解决select 查询字段 必须和insert中参数必须一一匹配问题
        //所有参数初始为null
        ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(itemDtl.getInsertSql());
        List<String> parameterNames = CustomParsedSql.getParameterNames(parsedSql);
        Map<String, Object> paramMap = new HashMap<>();
        if (null != parameterNames && parameterNames.size() > 0) {
            for (String param : parameterNames) {
                paramMap.put(param, null);
            }
        }
        DataSource dataSource = DbUtil.getDataSource(itemDtl.getDbKeyTo());
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
        Map[] mm = new HashMap[data.size()];
        for (int i = 0; i < data.size(); i++) {
            Map pMap = (Map) data.get(i);
            Map<String, Object> mMap = new HashMap<>();
            mMap.putAll(paramMap);
            mMap.putAll(pMap);
            mm[i] = mMap;
        }
        log.debug("[{}],write{}行数据", itemDtl.getItemName(), data.size());
        namedParameterJdbcTemplate.batchUpdate(itemDtl.getInsertSql(), mm);
        if (fail) {
            throw new RuntimeException("Planned failure");
        }
    }


    public WorkItem getItemDtl() {
        return itemDtl;
    }

    public void setItemDtl(WorkItem itemDtl) {
        this.itemDtl = itemDtl;
    }
}